package com.mzlalal.mybatis.interceptor.mybatis;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.mzlalal.mybatis.interceptor.prop.MyBatisPlusProperties;
import com.mzlalal.mybatis.interceptor.util.TenantIdService;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * mybatis plus 多租户实现
 * 去除ThreadLocal的实现,使用全局Request进行实现
 * 本质上还是ThreadLocal的实现
 *
 * @author Mzlalal
 * @date 2021/5/5 20:01
 **/
@Slf4j
@Component
public class MyTenantLineHandler implements TenantLineHandler {

    /**
     * 租户属性配置
     */
    private final MyBatisPlusProperties myBatisPlusProperties;

    private final TenantIdService tenantIdService;

    @Autowired
    public MyTenantLineHandler(MyBatisPlusProperties myBatisPlusProperties, TenantIdService tenantIdService) {
        this.myBatisPlusProperties = myBatisPlusProperties;
        this.tenantIdService = tenantIdService;
    }

    @Override
    public Expression getTenantId() {
        return new StringValue(this.processRequestTenantId());
    }

    @Override
    public String getTenantIdColumn() {
        return myBatisPlusProperties.getTenantIdDbColumnName();
    }

    /**
     * 处理request中的租户ID
     * 租户ID来源于application.prop中的配置,
     *
     * @return 字符串 当前用户的租户ID
     */
    private String processRequestTenantId() {
        return tenantIdService.getCurrentReqTenantId();
    }
}
